# -*- coding: utf-8 -*-
# coding:utf-8
import time
import json
import wejudge
import wejudge.kernel.general as kernel
import wejudge.apps.moss.models as MossModel
import wejudge.apps.asgn.models as AsgnModel
import wejudge.apps.contest.models as ContestModel
import MossLib
import MossSpider


__author__ = 'lancelrq'


class MossProvider(kernel.ViewerFramework):

    def __init__(self, request):
        kernel.ViewerFramework.__init__(self, request)

    def index(self):
        """
        Moss首页
        :return:
        """
        self._action = kernel.const.VIEW_ACTION_RENDER
        self._template_file = 'moss/index.html'
        self._context = {
        }

    def add_queue(self):
        """
        发起查重队列
        :return:
        """
        self._action = kernel.const.VIEW_ACTION_JSON
        method = "contest"
        id = self._request.GET.get("id")
        try:
            id = int(id)
        except:
            self._result = kernel.RESTStruct(False, msg="ID Error.")
            return

        if method == "contest":
            contest = ContestModel.Contest.objects.filter(id=id)
            if not contest.exists():
                self._result = kernel.RESTStruct(False, msg="Contest don't exists.")
                return
            contest = contest[0]
            # 创建记录
            task = MossModel.MossTasks()
            task.user = self._user_session.entity
            task.create_time = int(time.time())
            task.name = "test"
            task.setting_ratio = 0
            task.model_type = 'asgn'
            task.model_id = id
            task.save()
            # 初始化Storage
            status_storage = kernel.LocalStorage(kernel.const.USER_UPLOADCODE_DIR, "")
            moss_status_storage = kernel.LocalStorage(kernel.const.MOSS_STORAGE, str(task.id))
            # 遍历所有符合条件的status
            judge_status = contest.judge_status.filter(flag=0)
            for status in judge_status:
                tfn = "%s.%s" % (status.id, kernel.const.SOURCE_CODE_EXTENSION[status.lang])
                sfn = status_storage.get_current_path() + status.code_path
                moss_status_storage.clone_file(tfn, sfn)
            MossProvider.moss_worker.delay(task.id)

        self._result = kernel.RESTStruct(True)

    @staticmethod
    @wejudge.celery_app.task(name="moss_worker")
    def moss_worker(moss_queue_id):
        task = MossModel.MossTasks.objects.filter(id=moss_queue_id)
        if not task.exists():
            print "MOSS task item don't exists."
            return False
        task = task[0]
        task.status = 1         # Analyzing
        task.start_analysis_time = int(time.time())
        task.save()
        moss_status_storage = kernel.LocalStorage(kernel.const.MOSS_STORAGE, str(task.id))
        code_path = moss_status_storage.get_current_path()
        lib = MossLib.MOSS()
        lib.setLanguage('c')
        lib.addByWildcard(code_path + '/*')
        lib.setCommentString("WeJudge MOSS task")
        url = lib.send()
        print "AA%sBB" % url
        spider = MossSpider.StanfordMossSpider(url)
        result_list = spider.getResult()
        match_list = spider.getMatches(result_list)
        datas = {
            "url": url,
            "result_list": result_list,
            "match_list": match_list
        }
        moss_result_storage = kernel.LocalStorage(kernel.const.MOSS_STORAGE, "result")
        moss_result_storage.new_file("%s.json" % task.id, json.dumps(datas))
        task.status = 3
        task.save()
        return True
